import { fromEvent, merge } from "rxjs";
import { map, switchMap, startWith, distinctUntilChanged } from "rxjs/operators";
import { getLogger, randomInterval } from "../utils";

type Action = "cook" | "work";

function createBtn(name: Action) {
    const btn = document.createElement("button");
    btn.innerText = name;
    document.body.appendChild(btn);
    btn.style.margin = "20px";
    return btn;
}

const log0 = getLogger("Purpose");
log0("An example demonstrating switchMap with higher order observables");

const cookBtn = createBtn("cook");
const workBtn = createBtn("work");

const log = getLogger("currently doing");
log("resting");

const startCook$ = fromEvent(cookBtn, "click", e => "cook" as Action);
const startWork$ = fromEvent(workBtn, "click", e => "work" as Action);

function simulateDoing(a: Action) {
    return randomInterval().pipe(
        startWith(0),
        map((idx) => `${a}ing item ${idx}`)
    );
}

merge(startCook$, startWork$)
    .pipe(
        distinctUntilChanged(),
        switchMap(e => simulateDoing(e))
    )
    .subscribe(log);


